﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PersonalAccounting.Controls
{
    public partial class DoubleTextBox : TextBox
    {
        public DoubleTextBox()
        {
            InitializeComponent();
        }

        public DoubleTextBox(Container container)
        {
            container.Add(this);
            InitializeComponent();
        }

        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            // números
            if (e.KeyChar > 10)
            {
                if (e.KeyChar != '.' && e.KeyChar != ',')
                {
                    if (e.KeyChar < '0' || e.KeyChar > '9')
                    {
                        e.Handled = true;
                        return;
                    }
                }

                // cambia '.' por ','
                if (e.KeyChar == '.')
                    e.KeyChar = ',';

                // valida cantidad de decimales
                int i = Text.IndexOf(',');
                if (i >= 0)
                {
                    if (e.KeyChar == ',')
                    {
                        e.Handled = true;
                        return;
                    }
                    if (Text.Length > i)
                    {
                        if (Text.Substring(i + 1).Length > 1)
                            e.Handled = true;
                    }
                }
            }
        }

        public double Value
        {
            get
            {
                try
                {
                    return double.Parse(Text);
                }
                catch
                {
                    return 0;
                }
            }
            set
            {
                Text = value.ToString();
            }
        }

    }
}